<template>
	<view class="page">
		<!-- 地图全屏 -->
		<map class="map" :latitude="center.latitude" :longitude="center.longitude" :scale="17" show-location
			:enable-scroll="true" :enable-rotate="false" :enable-overlooking="false" :enable-zoom="true" />

		<!-- WotDesign 浮动面板 -->
		<wd-floating-panel :contentDraggable="false" v-model:height="height" :anchors="anchors"
			@heightChange="handleHeightChange">
			<view class="inner-content">
				<!-- 步数 -->
				<view class="big-num">{{ diffSteps }}</view>
				<view class="sub">步数</view>

				<!-- 左右两列：用时 / 配速 -->
				<view class="row">
					<view class="cell">
						<view class="val">{{ durationText }}</view>
						<view class="label">用时</view>
					</view>
					<view class="cell">
						<view class="val">{{ paceText }}</view>
						<view class="label">配速</view>
					</view>
				</view>

				<!-- 操作区 -->
				<view class="btns">
					<wd-button type="danger" round size="large" class="mr" @click="onFinish">结束</wd-button>
					<wd-button type="success" round size="large" @click="onToggle">
						{{ paused ? '继续' : '暂停' }}
					</wd-button>
				</view>
			</view>
		</wd-floating-panel>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted,
		onUnmounted,
		nextTick
	} from 'vue'
	import {
		useAppStore
	} from '@/stores/app'
	import {
		fetchTodaySteps
	} from '@/utils/werun'
	import {
		formatDuration,
		formatPace
	} from '@/utils/time'
	import {
		onLoad
	} from '@dcloudio/uni-app' // ← 获取 courseId

	/* ================ Pinia ================ */
	const store = useAppStore()

	/* ================ 路由参数（课程ID，可为空） ================ */
	const courseId = ref('')
	onLoad((q) => {
		courseId.value = q?.courseId || ''
	})

	/* ================ 小工具 ================ */
	const pad2 = (n) => (n < 10 ? '0' + n : '' + n)
	const nowDateStr = () => {
		const d = new Date()
		return `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`
	}
	const nowTimeStr = () => {
		const d = new Date()
		return `${pad2(d.getHours())}:${pad2(d.getMinutes())}`
	}
	const normalizeDuration = (s) => String(s).replace(/:/g, '：')

	/* （可选）记录页路由：用于无上一页时跳转 */
	const RECORDS_URL = '/pages/run/index'
	const RECORDS_IS_TAB = false

	function safeGoToRecords() {
		const pages = getCurrentPages()
		if (pages.length > 1) return uni.navigateBack()
		if (RECORDS_IS_TAB) return uni.switchTab({
			url: RECORDS_URL
		})
		uni.redirectTo({
			url: RECORDS_URL,
			fail() {
				uni.reLaunch({
					url: RECORDS_URL
				})
			}
		})
	}

	/* ================ 面板高度控制 ================ */
	const height = ref(0)
	const windowHeight = ref(0)
	const anchors = ref([])
	const handleHeightChange = (e) => {}
	onMounted(() => {
		const sys = uni.getSystemInfoSync()
		windowHeight.value = sys.windowHeight
		anchors.value = [
			Math.round(0.28 * windowHeight.value),
			Math.round(0.4 * windowHeight.value),
			Math.round(0.7 * windowHeight.value)
		]
		nextTick(() => {
			height.value = anchors.value[1]
		})
	})

	/* ================ 地图定位 ================ */
	const center = ref({
		latitude: 20.0433,
		longitude: 110.1999
	})
	onMounted(() => {
		uni.getLocation({
			type: 'gcj02',
			success: (r) => {
				center.value = {
					latitude: r.latitude,
					longitude: r.longitude
				}
			}
		})
	})

	/* ================ 步数逻辑（B 方案对齐基准） ================ */
	const KEY_BASE = 'RUN_BASE_STEPS'

	function todayStartTs() {
		const d = new Date();
		d.setHours(0, 0, 0, 0);
		return d.getTime()
	}
	const baseSteps = ref(0)
	const currentSteps = ref(0)
	const diffSteps = computed(() => Math.max(0, currentSteps.value - baseSteps.value))

	async function initBaseSteps() {
		const day = todayStartTs()
		const cache = uni.getStorageSync(KEY_BASE)
		if (cache && cache.day === day) {
			baseSteps.value = cache.base
		} else {
			const today = await fetchTodaySteps()
			baseSteps.value = Number(today) || 0
			uni.setStorageSync(KEY_BASE, {
				day,
				base: baseSteps.value
			})
		}
	}
	async function updateSteps() {
		try {
			const today = await fetchTodaySteps()
			currentSteps.value = Number(today) || 0
		} catch (e) {
			console.warn('获取步数失败', e)
		}
	}
	let tSteps = null

	/* ================ 用时 / 暂停 / 配速 ================ */
	const paused = ref(false)
	const durationMs = ref(0)
	let tDuration = null
	let pausedOffset = 0
	let pauseStart = 0

	function onToggle() {
		paused.value = !paused.value
		if (paused.value) pauseStart = Date.now()
		else pausedOffset += Date.now() - pauseStart
	}
	const durationText = computed(() => formatDuration(durationMs.value))
	const paceText = computed(() => {
		const stepLength = 0.7
		return formatPace(durationMs.value, diffSteps.value * stepLength)
	})

	/* ================ 点击“结束”：写入跑步记录 + 更新课程步数 + 更新今日步数 ================ */
	function onFinish() {
		if (diffSteps.value <= 0) {
			return uni.showToast({
				title: '本次步数为 0',
				icon: 'none'
			})
		}

		const stepLength = 0.7
		const meters = diffSteps.value * stepLength
		const distKm = (meters / 1000).toFixed(2)

		// —— 快照（弹窗期间数值不变） —— 
		const stepsAtFinish = diffSteps.value
		const durationAtFinish = durationText.value
		const paceAtFinish = paceText.value

		// 即将写入的记录
		const rec = {
			id: `r-${nowDateStr()}-${Date.now().toString().slice(-5)}`,
			date: nowDateStr(),
			time: nowTimeStr(),
			steps: stepsAtFinish,
			duration: normalizeDuration(durationAtFinish), // 'HH：MM：SS'
			pace: paceAtFinish
		}

		uni.showModal({
			title: '本次跑步',
			content: `步数：${stepsAtFinish}\n距离：${distKm} km\n用时：${durationAtFinish}\n配速：${paceAtFinish}`,
			success: ({
				confirm
			}) => {
				if (!confirm) return

				// 1) 跑步记录
				store.addRunRecord(rec)

				// 2) 课程进度（有 courseId 才加）
				if (courseId.value) {
					store.addCourseSteps({
						courseId: courseId.value,
						delta: stepsAtFinish
					})
				}

				// 3) 今日步数缓存（首页会先 set，当天多次运动就增量加）
				store.addTodaySteps(stepsAtFinish)

				// 返回列表
				safeGoToRecords()
			}
		})
	}

	/* ================ 生命周期（关键：对齐基准） ================ */
	onMounted(async () => {
		await initBaseSteps()
		await updateSteps()

		// 开始时把“当前读数”设置为新的基准，初始差值为 0
		baseSteps.value = currentSteps.value
		uni.setStorageSync(KEY_BASE, {
			day: todayStartTs(),
			base: baseSteps.value
		})

		tSteps = setInterval(updateSteps, 5000)

		const startTs = Date.now()
		tDuration = setInterval(() => {
			if (!paused.value) durationMs.value = Date.now() - startTs - pausedOffset
		}, 1000)
	})
	onUnmounted(() => {
		if (tSteps) clearInterval(tSteps)
		if (tDuration) clearInterval(tDuration)
	})
</script>


<style scoped>
	.page {
		position: relative;
		width: 100vw;
		height: 100vh;
	}

	.map {
		position: absolute;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
		width: 100%;
		height: 100%;
	}

	/* 浮动面板内容 */
	.inner-content {
		padding: 1rem;
		text-align: center;
	}

	.big-num {
		font-size: 84rpx;
		font-weight: 800;
		margin-top: 12rpx;
		color: #111;
	}

	.sub {
		font-size: 28rpx;
		color: #111;
		margin-top: 8rpx;
		letter-spacing: 2rpx;
	}

	.row {
		display: flex;
		justify-content: space-between;
		margin-top: 32rpx;
	}

	.cell {
		width: 48%;
	}

	.val {
		font-size: 42rpx;
		font-weight: 700;
		color: #111;
	}

	.label {
		margin-top: 8rpx;
		font-size: 26rpx;
		color: #666;
	}

	.btns {
	  margin-top: 44rpx;
	  display: flex;
	  justify-content: center;
	  align-items: center;
	  gap: 40rpx; /* 两个按钮之间的间距 */
	}

</style>